<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" />
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="open('add')" v-hasPermi="[basicSetupAuthList.profit_setting.add]">
          <div class="dk-iconfont icon-Plus"></div>
          新增
        </VButton>
        <VButton @click="handleCopy()" v-hasPermi="[basicSetupAuthList.profit_setting.copy]">
          <div class="dk-iconfont icon-Copy"></div>
          复制
        </VButton>
        <VButton @click="handleStaus(1)" v-hasPermi="[basicSetupAuthList.profit_setting.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
           启用
        </VButton>
        <VButton @click="handleStaus(2)" v-hasPermi="[basicSetupAuthList.profit_setting.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </VButton>
        <VButton type="" class="ml-auto" style="margin-left: auto" @click="onImport" v-hasPermi="[basicSetupAuthList.profit_setting.import]">
          <div class="dk-iconfont icon-Download"></div>
          导入
        </VButton>
        <VButton type="" @click="importHandleClick" v-hasPermi="[basicSetupAuthList.profit_setting.export]">
          <div class="dk-iconfont icon-Upload"></div>
            导出
        </VButton>
      </template>
    </VTable>
    <!-- 详情弹窗 -->
    <ComModal ref="ComModalRef" :originOption="originOption" @query="query"></ComModal>

    <!-- 日志/ -->
    <Log dialog v-model="logVisible" :autoLoad="false" tag="performance_indicator" :business_id="logId" />

    <performance ref="performanceRef"></performance>
    <showPersonnel ref="showPersonnelRef"></showPersonnel>
    <!-- 导入 -->
    <DialogImport ref="dialogImportRef" v-if="visibleImport" tpl_name="业绩报表模板.xlsx" oss_key="import/kpi/" :imporApi="kpiImport" @query="query" />
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>
<script name="Basic-setupProfit-setting" setup lang="jsx">
import { kpiIndex, kpiStatus, kpiDel, kpiLog, kpiImport } from "./api/index"
import { ElMessage, ElMessageBox } from "element-plus"
import { basicSetupAuthList } from "@/Auth/basic-setup.js"

// 新增/编辑弹窗
import ComModal from "./components/ComModal.vue"
const ComModalRef = ref()
const open = (type, id) => {
  ComModalRef.value.open(type, id)
}

// 查看日志
import Log from "@/components/Log/index.vue"
const logVisible = ref(false)
const logId = ref("")
const viewLog = (item) => {
  logId.value = item.id
  logVisible.value = true
}

// 人员完成情况
import performance from "./components/performance"
const performanceRef = ref()
const viewFinsh = (id) => {
  performanceRef.value.open(id)
}
// 所属部门/人员
import showPersonnel from "./components/showPersonnel"
const showPersonnelRef = ref()
const viewPersonel = (row) => {
  showPersonnelRef.value.open(row)
}

// 导入
import DialogImport from "./components/DialogImport/index.vue"
const dialogImportRef = ref()
const visibleImport = ref(false)
const onImport = async () => {
  visibleImport.value = true
  nextTick(() => {
    // let params = { tpl_name: "业绩报表模板.xlsx" }
    // dialogImportRef.value.open()
    dialogImportRef.value.open()
  })
}

// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = tableRef.value.getQueryForm()
  DerivedCenterRef.value.open({
    tag_name: "performance_indicators",
    condition,
  })
}

import XForm from "@/components/XForm/index.vue"
const formData = ref({})
const formOption = ref({ inline: true })
const publicStyle = { style: { width: "240px" } }
const fieldList = ref([
  {
    field: "indicator_type",
    type: "select",
    options: { placeholder: "指标" },
    // multiple: true,
    originField: "kpi_indicator_type",
    style: { width: "140px" },
  },
  {
    field: "target_type",
    type: "select",
    // clearable: false,
    options: { placeholder: "目标类型" },
    originField: "kpi_target_type",
    style: { width: "140px" },
    // change: (e) => {
    //   let form = tableRef.value.getForm()
    //   form.index_ids = []
    //   tableRef.value.setForm(form)
    // },
  },

  // {
  //   field: "index_ids",
  //   type: "cascader",
  //   itemProps: { placeholder: "所属人员" },
  //   style: { width: "200px" },
  //   show: ({ model }) => model.target_type == 2,
  // },
  // {
  //   field: "index_ids",
  //   type: "cascader",
  //   cascaderType: "department",
  //   itemProps: { placeholder: "所属部门" },
  //   style: { width: "200px" },
  //   show: ({ model }) => model.target_type == 1,
  // },

  {
    field: "time_range",
    type: "dateTimeRangeNorm",
    select: [{ label: "时间范围	", value: "time_range" }],
    selectStyle: { width: "100px" },
  },
  {
    field: "creator_ids",
    type: "cascader",
    itemProps: { placeholder: "创建人" },
  },
  {
    field: "create_time",
    type: "dateTimeRangeNorm",
    select: [{ label: "创建时间", value: "create_time" }],
    selectStyle: { width: "100px" },
  },
])

const tableOptins = reactive({
  formConfig: {
    data: {
      // target_type: 2,
      time_range: { type: "time_range", value: "" },
      create_time: { type: "create_time", value: "" },
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", width: 50, fixed: "left" },
    { field: "id", title: "ID", width: "60", fixed: "left" },
    { field: "indicator_type_desc", title: "业绩指标", width: "100", fixed: "left" },
    { field: "target_type_desc", title: "目标类型", width: "100", fixed: "left" },
    {
      field: "desired_target",
      title: "期望目标",
      width: "150",
      slots: {
        default: ({ row }) => (
          <div>
            {row.desired_target} {[1, 3].includes(row.indicator_type) ? row.currency : ""}
          </div>
        ),
      },
    },
    {
      field: "start_time",
      title: "时间范围",
      width: "120",
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row.start_time}</div>
              <div>{row.end_time}</div>
            </div>
          )
        },
      },
    },
    // {
    //   field: "department_id",
    //   title: "所属部门/人员",
    //   width: "120",
    //   slots: {
    //     default: ({ row }) => (
    //       <el-button type="primary" link onClick={() => viewPersonel(row)}>
    //         查看
    //       </el-button>
    //     ),
    //   },
    // },
    {
      field: "department_id",
      title: "所属部门",
      width: "250",
      slots: {
        default: ({ row }) => <VText value={row.department[0]} line={2} />,
      },
    },
    {
      field: "department_id",
      title: "目标负责人/所属人员",
      width: "250",
      slots: {
        default: ({ row }) => <VText value={row.target_owner_name} line={2} />,
      },
    },

    {
      field: "achieving_rate",
      title: "达成率",
      width: "120",
      slots: {
        default: ({ row }) => <div>{row.achieving_rate}%</div>,
      },
    },
    {
      title: "部门/人员目标完成情况",
      width: "170",
      slots: {
        default: ({ row }) => (
          <el-button type="primary" link onClick={() => viewFinsh(row.id)}>
            查看
          </el-button>
        ),
      },
    },
    {
      title: "状态",
      field: "status_desc",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status_desc === "启用"} />,
      },
    },
    {
      field: "creator",
      title: "创建人",
      width: 150,
      slots: {
        default: ({ row }) => <VText value={row.creator} />,
      },
    },
    { field: "create_time", title: "创建时间", width: "170" },
    {
      title: "操作",
      showOverflow: "title",
      width: 160,
      fixed: "right",
      text: "left",
      slots: {
        default: ({ row }) => {
          return (
            <div class="">
              <el-button type="primary" link onClick={() => open("edit", row.id)} v-hasPermi={[[basicSetupAuthList.profit_setting.edit]]}>
                编辑
              </el-button>
              <el-button type="primary" link onClick={() => viewLog(row)} v-hasPermi={[[basicSetupAuthList.profit_setting.log]]}>
                日志
              </el-button>
              <el-button type="danger" link onClick={() => handleDelete(row)} v-hasPermi={[[basicSetupAuthList.profit_setting.delete]]}>
                删除
              </el-button>
            </div>
          )
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page, form }) => {
        let res = await kpiIndex({ ...form, ...page })
        res.data.forEach((item) => {
          if (item.target_type == 1) {
            item.target_owner_name = item.target_owner.map((v) => v.substring(v.lastIndexOf("/") + 1)).join("，")
            item.department = item.target_values.map((v) => v.name)
          } else {
            item.target_owner_name = item.target_values.map((v) => v.name.substring(v.name.lastIndexOf("/") + 1)).join("，")
            item.department = item.target_values.map((v) => v.name.substring(0, v.name.lastIndexOf("/")))
          }
        })
        console.log(res.data)

        return res
      },
    },
  },
})

// 获取

import { getEnum } from "@/utils/enumUtils"
const originOption = ref({})
const fetchOption = async () => {
  let keys = ["kpi_indicator_type", "kpi_target_type"]
  let data = await getEnum(keys)
  keys.forEach((key) => {
    originOption.value[key] = data[key]
  })
}
fetchOption()

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}
// 复制
const handleCopy = () => {
  const records = getSelectRow().map((i) => i.id)
  if (records.length != 1) return ElMessage.error("只能复制一条记录")
  ComModalRef.value.open("copy", records[0])
}
// 启用禁用
const handleStaus = async (status) => {
  const ids = getSelectRow().map((i) => i.id)
  if (ids.length == 0) return ElMessage.error("至少选择一项")
  try {
    await kpiStatus({ ids, status })
    ElMessage.success("操作成功")
    query()
  } catch (e) {
    throw Error(e)
  }
}

const tableRef = ref()
// 查询
const query = () => {
  tableRef?.value.query()
}

// 删除
const handleDelete = ({ id }) => {
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      const res = await kpiDel({ id })
      ElMessage.success(res?.data?.message || "操作成功")
      query()
    } catch (e) {
      throw Error(e)
    }
  })
}
</script>
<style lang="scss" scoped></style>
